package com.ma.chapter8.semaphore;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Semaphore;

import static com.ma.util.Sleeper.sleep;

/**
 * @ClassName TestSemaphore
 * @Author: mayongqiang
 * @DATE 2022/3/26 15:16
 * @Description: 信号量测试
 */
@Slf4j(topic = "m.TestSemaphore")
public class TestSemaphore {
    public static void main(String[] args) {
        // 3个共享许可
        Semaphore semaphore = new Semaphore(3);

        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                try {
                    semaphore.acquire();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                try {
                    log.debug("running...");
                    sleep(1);
                    log.debug("end...");
                } finally {
                    semaphore.release();
                }
            }).start();
        }
    }
}
